#ifndef CONFIG_IO_CPP
#define CONFIG_IO_CPP
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;

class configIO
{
	protected:
		ifstream configIn;
		ofstream configOut;
		map<string ,string> dbConfig;
		map<string ,string> fileConfig;
		map<string ,string> recentFileConfig;
		map<string ,string> *tempMap;
		string configline;

		void readConf()
		{
			while(!configIn.eof())
			{
				getline(configIn,configline,'\n');
				cout<<"read a line: "<<configline<<endl;
				switch(configline[0])
				{
					case '#':
						break;
					case '[':
						parseConfig();
						break;
					default:
						break;
				}
			}
		}

		void parseConfig()
		{
			if(configline=="[Database Configuration]")
			{
				cout<<"got a match"<<endl;
				tempMap = &dbConfig;
				loadConfigurationOptions();
			}
			else if(configline=="[File Configuration]")
			{
				cout<<"got a match"<<endl;
				tempMap = &fileConfig;
				loadConfigurationOptions();
			}
			else if(configline=="[Recent Files]")
			{
				cout<<"got a match"<<endl;
				tempMap = &recentFileConfig;
				loadConfigurationOptions();
			}
			else
			{
				cout<<"no match"<<endl;
				cout<<configline<<endl;
			}

		}

		void loadConfigurationOptions()
		{
			string cline;
			getline(configIn,cline,'\n');
			string cname,cval;
			while(cline[0]!='[')
			{
				if(cline[0]!='#')
				{
					splitString(cline, cname, cval);
					(*tempMap)[cname] = cval;
				}
				getline(configIn,cline,'\n');
			}
		}

		void splitString(string line, string &a, string &d)
		{
			vector<string> s;
			tokenizer<> t(line);
			for(tokenizer<>::iterator b=t.begin();b!=t.end();++b)
			{
				s.push_back(*b);
			}
			a=s[0];
			d=s[1];
		}
	public:
		const static int DATABASE_CONFIG = 1;
		const static int FILE_CONFIG = 2;
		const static int RECENT_FILES = 3;
		configIO(string pathname="/home/miyako/.mediabrowser/mediabrowser.conf")
		{
			configIn.open(pathname.c_str(),ios::in);
			tempMap = new map<string ,string>;
		}

		void start()
		{
			readConf();
		}

		void testConf()
		{
			for(map<string,string>::iterator x=dbConfig.begin();
							x!=dbConfig.end();x++)
			{
				cout<<(*x).first<<"     "<<x->second<<endl;
			}
		}

		string getValue(string s, int filetype)
		{
			switch(filetype)
			{
				case DATABASE_CONFIG:
					return dbConfig[s];
					break;
				case FILE_CONFIG:
					return fileConfig[s];
					break;
				case RECENT_FILES:
					return recentFileConfig[s];
					break;
				default:
					return NULL;
					break;
			}
		}
};
#endif
